﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Common
{
    public class WebHandleErrorAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// 重写异常处理方法 add by caoheyang 20150205   需要将该特性标注于各个controller上。
        /// </summary>
        /// <param name="filterContext">上下文对象  该类继承于ControllerContext</param>
        public override void OnException(ExceptionContext filterContext)
        {
            Log.Error(LogWriterFromFilter(filterContext.Exception));
            bool flag = filterContext.RequestContext.HttpContext.Request.IsAjaxRequest();
            if (flag)
            {
                //直接返回503，然后客户端判断，并添加SessionTimeout头
                filterContext.HttpContext.Response.AddHeader("ServerErr", "true");
                filterContext.Result = new HttpStatusCodeResult(500, filterContext.HttpContext.Server.UrlEncode("服务器发生未知错误，请稍后再试！"));
                return;
            }
            filterContext.Result = new RedirectResult("/error/err_500");
        }

        /// <summary>
        /// 捕获全局异常
        /// </summary>
        /// <param name="error"></param>
        public string LogWriterFromFilter(Exception error)
        {
            try
            {
                StringBuilder logstr = new StringBuilder("\r\n-----------------start----------------------\r\n");
                //异常发生地址
                logstr.Append("异常发生地址:").Append(HttpContext.Current.Request.Url.AbsoluteUri.ToString()).Append("\r\n");
                logstr.Append("请求类型:").Append(HttpContext.Current.Request.RequestType.ToString()).Append("\r\n");
                logstr.Append("异常:").Append(error.ToString()).Append("\r\n");
                logstr.Append("--------------------end---------------------\r\n");
                return logstr.ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
